package com.yirui.bridge.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * @author Dujie
 * @create 2021/11/3
 * @since 1.0.0
 */
@ChannelHandler.Sharable
@Slf4j
public class TcpChannelInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {


    private NettyTcpClient nettyClient;

    public void setNettyClient(NettyTcpClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
        //处理服务端返回的数据
        String val = Unpooled.copiedBuffer(ByteBufUtil.getBytes(in)).toString(CharsetUtil.UTF_8);
        log.debug("TCP收到服务器应答信息：{}", val);
        if (StringUtils.hasLength(val)) {
            nettyClient.setStatus(val.trim());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            log.info("channelInactive执行了" + ctx.name() + " | " + ctx.toString());


             ctx.close();
             ctx.disconnect();
            //super.channelInactive(ctx);
            nettyClient.setReconnectTime(System.currentTimeMillis());
            nettyClient.connect();

        } catch (Exception ex) {
            log.error("channelInactive异常： ", ex);
        }
    }
}
